using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using SKYPE4COMLib;
using System.Collections.Specialized;
using System.Diagnostics;

namespace Ajc {
    public partial class SettingsForm : Form, Logging, UserInterface {
        private Skyping skypingFunctions;
        private bool skipNextSilentModeChange = false;
        private bool shutdown = false;

        public SettingsForm() {
            InitializeComponent();

#if (DEV_MODE)            
            this.showLogBox.Checked = true;
#endif
        }

        public void setSkyping(Skyping skypeClass) {
            this.skypingFunctions = skypeClass;
            this.autoAcceptEnabled.Checked = this.skypingFunctions.AcceptIncomingCalls;
            this.autoJoinEnabled.Checked = this.skypingFunctions.JoinIncomingCalls;
            this.announceEnabled.Checked = this.skypingFunctions.AnnounceNewCaller;
            this.autoStartSkype.Checked = this.skypingFunctions.StartSkypeIfNeeded;
            this.waitingTime.Text = this.skypingFunctions.WaitingTimeBeforeAcceptCall.ToString();

            if (Ajc.Properties.Settings.Default.allowedUsers == null)
            {
                Ajc.Properties.Settings.Default.allowedUsers = new StringCollection();
            }
            if (Ajc.Properties.Settings.Default.allowedUsersEnabled) {
                this.skypingFunctions.AllowedUsers = Ajc.Properties.Settings.Default.allowedUsers;

                debug("Loaded allowed Users: " + Ajc.Properties.Settings.Default.allowedUsers.Count);
            } else {                
                debug("Allowed Users disabled.");
            }
            
            this.skypingFunctions.OnAttachStatusChanged += this.SkypeAttachStatusChanged;
            this.skypingFunctions.OnSilentModeChanged += this.SkypeSilentModeChanged;

            this.skypingFunctions.attachToSkype();
        }

        void SkypeSilentModeChanged(bool silentMode)
        {
            this.debug("Silent mode changed to: " + silentMode);
            this.skipNextSilentModeChange = true;
            this.silentMode.Checked = silentMode;
        }

        private void SkypeAttachStatusChanged(Ajc.Skyping.AttachStatus status) {
            this.debug("New attach status: " + status);
            this.editAllowedUsers.Enabled = (status == Skyping.AttachStatus.ATTACHED);
        }

        /// <summary>
        /// The user clicked the X on the form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SettingsForm_FormClosing(object sender, FormClosingEventArgs e) {
            if (! this.shutdown)
            {                
                this.shutdown = true;
                if (this.autoStopSkype.Checked)
                {
                    this.skypingFunctions.shutdownSkype();
                }

                Ajc.Properties.Settings.Default.Save();
            }
            System.Windows.Forms.Application.Exit();
        }

        private void aboutButton_Click(object sender, EventArgs e) {
            MessageBox.Show(
                "Skype Auto Conference Joiner v" + Program.VERSION + "\n" +
                "http://code.google.com/p/sacj",
                "About");            
        }


        #region Logging Member

        private void showBalloonTip(String title, String message) {
            showBalloonTip(title, message, 3);
        }

        private void showBalloonTip(String title, String message, int timeout) {
            trayIcon.BalloonTipTitle = title;
            trayIcon.BalloonTipText = message;
            trayIcon.ShowBalloonTip(timeout);
        }

        public void info(string logMessage) {
            showBalloonTip("Information", logMessage);
            logBox.AppendText(DateTime.Now.ToLongTimeString() + ": " + logMessage + "\n");
        }
        public void debug(string logMessage) {
            //showBalloonTip("Debug", logMessage);
            logBox.AppendText(DateTime.Now.ToLongTimeString() + " D: " + logMessage + "\n");
        }

        public void error(string logMessage) {
            showBalloonTip("Error", logMessage);
            logBox.AppendText(DateTime.Now.ToLongTimeString() + " ERROR: " + logMessage + "\n");
            // an error is critical, thus we open the settings window and show the console
            this.needUserAttention();
        }


        #endregion

        #region UserInterface Member

        public void needUserAttention() {
            this.ShowInTaskbar = true;
            this.WindowState = FormWindowState.Normal;
        }

        public void showMessageBoxModal(string message) {
            MessageBox.Show(message);
        }

        #endregion

        #region Checkboxes CheckedChanged

        private void autoAcceptEnabled_CheckedChanged(object sender, EventArgs e) {
            this.skypingFunctions.AcceptIncomingCalls = this.autoAcceptEnabled.Checked;
        }

        private void announceEnabled_CheckedChanged(object sender, EventArgs e) {
            this.skypingFunctions.AnnounceNewCaller = this.announceEnabled.Checked;
        }

        private void autoJoinEnabled_CheckedChanged(object sender, EventArgs e) {
            this.skypingFunctions.JoinIncomingCalls = this.autoJoinEnabled.Checked;
        }

        private void autoStartSkype_CheckedChanged(object sender, EventArgs e) {
            this.skypingFunctions.StartSkypeIfNeeded = this.autoStartSkype.Checked;
        }

        private void showLogBox_CheckedChanged(object sender, EventArgs e)
        {
            this.logBox.Visible = this.showLogBox.Checked;
        }

        private void silentMode_CheckedChanged(object sender, EventArgs e) {
            if (!this.skipNextSilentModeChange)
            {
                this.skypingFunctions.SilenMode = this.silentMode.Checked;
            }
            this.skipNextSilentModeChange = false;

            this.silentMode.Text = this.silentMode.Checked ? "Silent Mode: ON" : "Silent Mode: OFF";
        }

        #endregion

        private void quitItem_MouseClick(object o, EventArgs e) {
                System.Windows.Forms.Application.Exit();
        }

        private void toggleForm() {
            if (this.WindowState == FormWindowState.Minimized) {
                this.ShowInTaskbar = true;
                this.Show();
                this.WindowState = FormWindowState.Normal;
            } else {
                this.ShowInTaskbar = false;
                this.Hide();
                this.WindowState = FormWindowState.Minimized;
            }
        }

        private void editAllowedUsers_Click(object sender, EventArgs e) {            
            AllowedUsersForm allowedUsersForm = new AllowedUsersForm(Ajc.Properties.Settings.Default.allowedUsers,
                this.skypingFunctions.getContacts());
            if (allowedUsersForm.ShowDialog() == DialogResult.OK)
            {
                StringCollection allowedUsers = allowedUsersForm.AllowedUsers;
                // save the new allowed users list
                Ajc.Properties.Settings.Default.allowedUsers = allowedUsers;

                if (allowedUsersForm.AllowedUsersEnabled)
                {
                    this.skypingFunctions.AllowedUsers = allowedUsers;
                }
            }
        }

        private void waitingTime_TextChanged(object sender, EventArgs e)
        {
            try
            {
                int time = int.Parse(this.waitingTime.Text);
                this.skypingFunctions.WaitingTimeBeforeAcceptCall = time;
            }
            catch (FormatException excp)
            {
                MessageBox.Show("Please enter a positive number.");
            }
            
        }

        /// <summary>
        /// Used to hide the form and taskbar icon when the form is minimized.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SettingsForm_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.ShowInTaskbar = false;
                this.Hide();
            }
        }

        private void trayIcon_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                if (! this.Visible)
                {
                    this.Show();                    
                    this.ShowInTaskbar = true;
                    this.WindowState = FormWindowState.Normal;
                    this.Activate();
                }
                else
                {
                    this.Hide();      
                    this.ShowInTaskbar = false;                                  
                }
            }
        }

        private void settingsItem_Click(object sender, EventArgs e)
        {
            this.Show();
            this.ShowInTaskbar = true;         
            this.WindowState = FormWindowState.Normal;
            this.Activate();
        }
    }
}